package org.jeecg.modules.demo.com.kunpeng.controller;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.demo.com.kunpeng.entity.ProjectPurchaseApply;
import org.jeecg.modules.demo.com.kunpeng.entity.dto.ProjectPurchaseQueryDTO;
import org.jeecg.modules.demo.com.kunpeng.vo.ProjectPurchaseDetailsVO;
import org.jeecg.modules.demo.com.kunpeng.vo.ProjectPurchaseListQueryVO;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.com.kunpeng.entity.ProjectPurchase;
import org.jeecg.modules.demo.com.kunpeng.vo.ProjectPurchasePage;
import org.jeecg.modules.demo.com.kunpeng.service.IProjectPurchaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;


 /**
 * @Description: 项目采购表
 * @Author: jeecg-boot
 * @Date:   2022-12-15
 * @Version: V1.0
 */
@Api(tags="项目采购表")
@RestController
@RequestMapping("/com.kunpeng/projectPurchase")
@Slf4j
public class ProjectPurchaseController {
	@Autowired
	private IProjectPurchaseService projectPurchaseService;
	
	/**
	 * 分页列表查询
	 *
	 * @param projectPurchase
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "项目采购表-分页列表查询")
	@ApiOperation(value="项目采购表-分页列表查询", notes="项目采购表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ProjectPurchase>> queryPageList(ProjectPurchase projectPurchase,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ProjectPurchase> queryWrapper = QueryGenerator.initQueryWrapper(projectPurchase, req.getParameterMap());
		Page<ProjectPurchase> page = new Page<ProjectPurchase>(pageNo, pageSize);
		IPage<ProjectPurchase> pageList = projectPurchaseService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param projectPurchasePage
	 * @return
	 */
	@AutoLog(value = "项目采购表-添加")
	@ApiOperation(value="项目采购表-添加", notes="项目采购表-添加")
    //@RequiresPermissions("com.kunpeng:project_purchase:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ProjectPurchasePage projectPurchasePage) {
		System.out.println("projectPurchasePage:"+projectPurchasePage.toString());
		ProjectPurchase projectPurchase = new ProjectPurchase();
		BeanUtils.copyProperties(projectPurchasePage, projectPurchase);
		projectPurchaseService.saveMain(projectPurchase,projectPurchasePage.getProjectPurchaseApplyList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param projectPurchasePage
	 * @return
	 */
	@AutoLog(value = "项目采购表-编辑")
	@ApiOperation(value="项目采购表-编辑", notes="项目采购表-编辑")
    //@RequiresPermissions("com.kunpeng:project_purchase:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ProjectPurchasePage projectPurchasePage) {
		ProjectPurchase projectPurchase = new ProjectPurchase();
		BeanUtils.copyProperties(projectPurchasePage, projectPurchase);
		ProjectPurchase projectPurchaseEntity = projectPurchaseService.getById(projectPurchase.getId());
		if(projectPurchaseEntity==null) {
			return Result.error("未找到对应数据");
		}
		projectPurchaseService.updateMain(projectPurchase,projectPurchasePage.getProjectPurchaseApplyList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	/*@AutoLog(value = "项目采购表-通过id删除")
	@ApiOperation(value="项目采购表-通过id删除", notes="项目采购表-通过id删除")
    //@RequiresPermissions("com.kunpeng:project_purchase:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		projectPurchaseService.delMain(id);
		return Result.OK("删除成功!");
	}*/
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	/*@AutoLog(value = "项目采购表-批量删除")
	@ApiOperation(value="项目采购表-批量删除", notes="项目采购表-批量删除")
    //@RequiresPermissions("com.kunpeng:project_purchase:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.projectPurchaseService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}*/
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目采购表-通过id查询")
	@ApiOperation(value="项目采购表-通过id查询", notes="项目采购表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ProjectPurchase> queryById(@RequestParam(name="id",required=true) String id) {
		ProjectPurchase projectPurchase = projectPurchaseService.getById(id);
		if(projectPurchase==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(projectPurchase);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param projectPurchase
    */
    //@RequiresPermissions("com.kunpeng:project_purchase:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ProjectPurchase projectPurchase) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<ProjectPurchase> queryWrapper = QueryGenerator.initQueryWrapper(projectPurchase, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<ProjectPurchase> projectPurchaseList = projectPurchaseService.list(queryWrapper);

      // Step.3 组装pageList
      List<ProjectPurchasePage> pageList = new ArrayList<ProjectPurchasePage>();
      for (ProjectPurchase main : projectPurchaseList) {
          ProjectPurchasePage vo = new ProjectPurchasePage();
          BeanUtils.copyProperties(main, vo);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "项目采购表列表");
      mv.addObject(NormalExcelConstants.CLASS, ProjectPurchasePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("项目采购表数据", "导出人:"+sysUser.getRealname(), "项目采购表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("com.kunpeng:project_purchase:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ProjectPurchasePage> list = ExcelImportUtil.importExcel(file.getInputStream(), ProjectPurchasePage.class, params);
              for (ProjectPurchasePage page : list) {
                  ProjectPurchase po = new ProjectPurchase();
                  BeanUtils.copyProperties(page, po);
                  projectPurchaseService.saveMain(po,page.getProjectPurchaseApplyList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  * 根据关键字模糊查询
	  *
	  * @param projectPurchaseQueryDTO
	  * @param pageNo
	  * @param pageSize
	  * @return
	  */
	 @ApiOperation(value = "项目采购表-根据关键字分页列表查询", notes = "项目采购表-根据关键字分页列表查询")
	 @PostMapping(value = "/listByKeyWords")
	 public Result<IPage<ProjectPurchaseListQueryVO>> queryPageList(@RequestBody ProjectPurchaseQueryDTO projectPurchaseQueryDTO,
																	@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
																	@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		 log.info("开始处理根据关键字查询项目列表请求...");
		 System.out.println("projectPurchaseQueryDTO:"+projectPurchaseQueryDTO.toString());

		 Result<Page<ProjectPurchaseListQueryVO>> result = new Result<Page<ProjectPurchaseListQueryVO>>();
		 Page<ProjectPurchaseListQueryVO> pageList = new Page<ProjectPurchaseListQueryVO>(pageNo, pageSize);
		 pageList = projectPurchaseService.listByKeyWords(pageList, projectPurchaseQueryDTO);//通知公告消息
		 if (pageList.getRecords().size() == 0) {
			 return Result.ok("没有符合条件的数据，请重新输入！");
		 }
		 log.info("查询当前页：" + pageList.getCurrent());
		 log.info("查询当前页数量：" + pageList.getSize());
		 log.info("查询结果数量：" + pageList.getRecords().size());
		 log.info("数据总数：" + pageList.getTotal());
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return Result.ok(pageList);
	 }

	 /**
	  * 根据id获取项目采购详情
	  * @param id
	  * @return
	  */
	 @ApiOperation(value = "项目采购表-获取项目采购详情", notes = "项目采购表-获取项目采购详情")
	 @GetMapping(value = "/selectDetailsById")
	 public Result<ProjectPurchaseDetailsVO> selectDetailsById(String id){
	 	log.info("开始处理根据项目采购id获取项目详情请求：");
		 ProjectPurchaseDetailsVO projectPurchaseDetailsVO = projectPurchaseService.selectProjectPurchaseDetailsById(id);
		 return Result.ok(projectPurchaseDetailsVO);
	 }


	 /**
	  * 根据项目采购id查询项目采购申请表数据
	  */
	 @ApiOperation(value = "项目采购申请表-获取项目采购申请表数据", notes = "项目采购申请表-获取项目采购申请表数据")
	 @GetMapping(value = "/listProjectPurchaseByPPId")
	 public Result<List<ProjectPurchaseApply>> listProjectPurchaseByPPId(String PPId){
	 	log.info("处理根据项目采购id获取项目采购申请数据请求：");
		 List<ProjectPurchaseApply> projectPurchaseApplies = projectPurchaseService.listByPPId(PPId);
		 /*System.out.println("***********************ppid："+PPId);*/
		 for (ProjectPurchaseApply p:projectPurchaseApplies) {
			 log.info("返回的项目采购申请数据："+p.toString());
		 }
		 return Result.ok(projectPurchaseApplies);
	 }

	 /**
	  * 根据项目编号查询项目采购列表
	  */
	 @ApiOperation(value = "项目采购表-项目列表页面跳转", notes = "项目采购表-项目列表页面跳转")
	 @GetMapping(value = "/listByProjectId")
	 public Result<IPage<ProjectPurchaseListQueryVO>> listByProjectId(String projectId,
																	@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
																	@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		 log.info("开始处理根据关键字查询项目列表请求...");
		 Result<Page<ProjectPurchaseListQueryVO>> result = new Result<Page<ProjectPurchaseListQueryVO>>();
		 Page<ProjectPurchaseListQueryVO> pageList = new Page<ProjectPurchaseListQueryVO>(pageNo, pageSize);
		 pageList = projectPurchaseService.listByProjectId(pageList,projectId);//通知公告消息
		 if (pageList.getRecords().size() == 0) {
			 return Result.error("没有符合条件的数据，请重新输入！");
		 }
		 log.info("查询当前页：" + pageList.getCurrent());
		 log.info("查询当前页数量：" + pageList.getSize());
		 log.info("查询结果数量：" + pageList.getRecords().size());
		 log.info("数据总数：" + pageList.getTotal());
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return Result.ok(pageList);
	 }


 }
